// src/store/index.js
import { createStore } from 'vuex';
import axios from 'axios';

// 配置后端基准 URL
axios.defaults.baseURL = 'http://localhost:8080';

// 在请求拦截器中添加 Token
axios.interceptors.request.use((config) => {
  const token = localStorage.getItem('accessToken');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

export default createStore({
  state() {
    const userStr = localStorage.getItem('user');
    const userObj = userStr ? JSON.parse(userStr) : null;
    const accessToken = localStorage.getItem('accessToken') || null;
    const refreshToken = localStorage.getItem('refreshToken') || null;
    const isAuth = localStorage.getItem('isAuthenticated') === 'true';

    return {
      user: userObj,
      accessToken,
      refreshToken,
      isAuthenticated: isAuth,

      // ========== 新增: 用来存储背诵统计的数据 ==========
      reciteStats: null, 
    };
  },
  mutations: {
    SET_AUTH_DATA(state, payload) {
      state.user = payload.user || null;
      state.accessToken = payload.accessToken || null;
      state.refreshToken = payload.refreshToken || null;
      state.isAuthenticated = !!payload.accessToken;
    },
    CLEAR_AUTH_DATA(state) {
      state.user = null;
      state.accessToken = null;
      state.refreshToken = null;
      state.isAuthenticated = false;
    },
    UPDATE_USER(state, userData) {
      // 用于刷新用户信息后更新
      state.user = userData;
      localStorage.setItem('user', JSON.stringify(userData));
    },

    // ========== 新增: 用来在 state 中保存获取到的背诵统计 ==========
    SET_RECITE_STATS(state, stats) {
      state.reciteStats = stats;
    },
  },
  actions: {
    async sendVerificationEmail(_, email) {
      try {
        const res = await axios.post('/api/send-verification-email/', { email });
        return res.data;
      } catch (err) {
        throw err.response?.data || err;
      }
    },

    async register(_, payload) {
      try {
        const res = await axios.post('/api/register/', payload);
        return res.data;
      } catch (err) {
        throw err.response?.data || err;
      }
    },

    async login({ commit }, { email, password }) {
      try {
        const res = await axios.post('/api/login/', { email, password });
        const { tokens, user } = res.data;
        commit('SET_AUTH_DATA', {
          user,
          accessToken: tokens?.access,
          refreshToken: tokens?.refresh,
        });
        localStorage.setItem('accessToken', tokens?.access);
        localStorage.setItem('refreshToken', tokens?.refresh || '');
        localStorage.setItem('user', JSON.stringify(user));
        localStorage.setItem('isAuthenticated', 'true');
        return res.data;
      } catch (err) {
        throw err.response?.data || err;
      }
    },

    logout({ commit }) {
      commit('CLEAR_AUTH_DATA');
      localStorage.removeItem('accessToken');
      localStorage.removeItem('refreshToken');
      localStorage.removeItem('user');
      localStorage.removeItem('isAuthenticated');
    },

    /**
     * 获取当前用户全部的 DailyActivity
     * （若您决定不再使用 DailyActivity，可将此方法删除）
     */
    async fetchDailyActivities() {
      try {
        const res = await axios.get('/api/user/daily-activities/');
        // res.data: [{ id, user, date, words_learned, is_logged_in, is_words_learned }, ...]
        return res.data;
      } catch (err) {
        throw err.response?.data || err;
      }
    },

    /**
     * 点击“签到”
     */
    async checkIn() {
      try {
        const res = await axios.post('/api/user/checkin/');
        return res.data; // { detail: "签到成功！" }
      } catch (err) {
        throw err.response?.data || err;
      }
    },

    /**
     * 刷新用户信息
     * （如果需要在签到后更新用户资料，比如连续登录天数等）
     */
    async refreshUser({ commit }) {
      try {
        const res = await axios.get('/api/user/me/');
        // 假设您有 /api/user/me/ 这样的接口返回用户新信息
        // 例如: { username, email, consecutive_login_days, ... }
        commit('UPDATE_USER', res.data);
      } catch (err) {
        console.error('刷新用户信息失败', err);
      }
    },

    // ========== 新增: 从 recite app 获取背诵统计 ==========
    async fetchReciteStats({ commit }) {
      try {
        const res = await axios.get('/api/recite/stats/');
        // 后端返回形如:
        // {
        //   vocabulary_count: 123,
        //   yesterday_word_count: 7,
        //   daily_stats: [ {date: '2025-01-01', count:5}, ... ]
        // }
        commit('SET_RECITE_STATS', res.data);
        return res.data;
      } catch (err) {
        throw err.response?.data || err;
      }
    },
  },
  getters: {
    isLoggedIn: (state) => state.isAuthenticated,
    currentUser: (state) => state.user,

    // ========== 新增: 从 reciteStats 中取各字段，供组件使用 ==========
    reciteStats: (state) => state.reciteStats,
    vocabularyCount: (state) => (state.reciteStats ? state.reciteStats.vocabulary_count : 0),
    yesterdayWordCount: (state) => (state.reciteStats ? state.reciteStats.yesterday_word_count : 0),
    dailyStats: (state) => (state.reciteStats ? state.reciteStats.daily_stats : []),
  },
});
